// ============================== 数据表格相关方法 =============================

// 引用文件
import {
  export_json_to_excel
} from "../utils/Export2Excel"
import _ from "lodash"
import printJS from 'print-js'
import {
  EquipmentStatus,
  MessageType,
  WasteCharacteristics,
  PhysicalProperties,
  ContainerType,
  WarehouseCategory,
  AnnualWasteProductionScale,
  userDisalbe,
  CarType,
  LicensePlateColor,
} from "../utils/resource"
import { mapGetters } from "vuex";

export const pageMixin = {
  data() {
    return {
      pageSize: 10,
      currentPage: 1,
      total: 0,
      loading: false,
      id: "",
      disabled: true,
      tableData: [],
      ids: [],
      code: "",
      dataforExport: [],
      fileName: "",
      summaryWastCount: 0, // 用于显示当前页面废物总个数
      summaryWastWeight: 0 // 用于显示当前页面废物总重量
    }
  },
  computed: {
    ...mapGetters(["btn_list"]),
    deleteDisabled() {
      return this.ids.length === 0;
    },
  },
  methods: {
    buttonClick(method) {
      this[method]();
    },
    deleteChange({column}){
      console.log(column);
    },
    handleSelectionChange(value) {
      console.log(value,"handleSelectionChange");
      if (value.length !== 1) {
        this.disabled = true;
      } else {
        this.disabled = false;
        this.id = value[0].id;
        this.code = value[0].code;
      }
      this.ids = value
      this.dataforExport = value
    },
    async handleCurrentChange(value) {
      this.currentPage = value;
      await this.init();
    },
    async handleSizeChange(value) {
      this.pageSize = value;
      await this.init();
    },
    async search() {
      this.currentPage = 1;
      await this.init();
    },
    printData() {
      const html = document.querySelector('#table').innerHTML
      const div = document.createElement('div')
      const printDOMID = 'printDOMElement'
      div.id = printDOMID
      div.innerHTML = html

      const ths = div.querySelectorAll('.el-table__header-wrapper th')
      const ThsTextArry = []
      for (let i = 0, len = ths.length; i < len; i++) {
        if (ths[i].innerText !== '') ThsTextArry.push(ths[i].innerText)
      }

      // 删除多余的表头
      div.querySelector('.hidden-columns').remove()
      // 第一个表格的内容提取出来后已经没用了 删掉
      div.querySelector('.el-table__header-wrapper').remove()

      // 将第一个表格的内容插入到第二个表格
      let newHTML = '<tr>'
      for (let i = 0, len = ThsTextArry.length; i < len; i++) {
        newHTML += '<td style="text-align: center; font-weight: bold;width:100px">' + ThsTextArry[i] + '</td>'
      }

      newHTML += '</tr>'
      const ht = div.querySelector('.el-table__body-wrapper table')
      const list = ht.querySelectorAll("tr");
      for (const p of list) {
        p.querySelector("td").remove()
      }
      ht.insertAdjacentHTML('afterbegin', newHTML)

      // 将新的 DIV 添加到页面 打印后再删掉
      document.querySelector('body').appendChild(div)

      printJS({
        printable: printDOMID,
        type: 'html',
        headerStyle: 'text-align:center;color:#f00;width:100%;border:1px #000 solid;',
        scanStyles: false,
        style: '@media print{@page {size:landscape}} table tr td,th { border-collapse: collapse;text-align: center;border:1px #000 solid; };' // 表格样式
      })

      div.remove()
    },
    exportData() {
      const array = _.clone(this.$refs.multipleTable.columns);
      //删除无用列
      const arr = array.findIndex(item => item.label === "MSDS信息")
      if(arr>0){
        array.splice(arr, 1);
      }
      const arr2 = array.findIndex(item => item.label === "操作")
      if(arr2>0){
        array.splice(arr2, 1);
      }
      array.splice(0, 1);
      const tHeader = array.map(p => p.label)
      const filterVal = array.map(p => p.property)
      const list = this.dataforExport
      const data = this.formatJson(filterVal, list)

      export_json_to_excel({
        header: tHeader,
        data,
        autoWidth: true,
        bookType: "xlsx",
        filename: this.name
      })
    },
    exportDataTwo() {
      const array = _.clone(this.$refs.multipleTable.columns)//获取选择行所有数据(包括单选框)
      console.log(array,"array");
      array.splice(0, 1);//清除单选框
      console.log(array,"array.splice");
      const tHeader = array.map(p => p.label)//获取列表字段
      console.log(tHeader,"array.map(p => p.label)");
      const filterVal = array.map(p => p.property)//获取列表字段值
      console.log(filterVal,"array.map(p => p.property)");
      const list = this.dataforExport
      console.log(list,"this.dataforExport");
      const data = this.formatJson(filterVal, list)
      console.log(data,"this.formatJson(filterVal, list)");
      // export_json_to_excel({
      //   header: tHeader,
      //   data,
      //   autoWidth: true,
      //   bookType: "xlsx",
      //   filename: this.name
      // })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
       console.log("打印",v[j]);
        switch (j) {
          case "overTime":
          case "addTime":
          case "borrowTime":
          case "proExpirationTime":
          case "eomrpTime":
          case "createTime":
          case "updateTime":
            return this.parseDate(v[j]);
          case "status":
            return this.parseStatus(v[j]);
          case "type":
            return this.parseType(v[j]);
          case "containerCategory":
            return this.showContainerCategory(v[j]);
          case "physicalProperties":
            return this.showPhysicalProperties(v[j]);
          case "characteristicContent":
            return this.showCharacteristicContent(v[j]);
          case "warehouseCategory":
            return this.showType(v["type"]);
          case "sex":
            return this.parseSex(v[j]);
          case "disabled":
            return this.parseUserDisable(v[j]);
          case "weChatOpenId":
            return this.parseWeChat(v[j]);
          case "awpsId":
            return this.showAwps(v[j]);
          case "vehicleModel":
            return this.parseVehicleModel(v[j]);
          case "plateColor":
            return this.parsePlateColor(v[j]);
          case "useStatus":
            return this.parseUseStatus(v[j]);
          case "carStatus":
            return this.parseCarStatus(v["status"]);
          case "enterpriseCategoryContent":
            return v["enterpriseCategroyList"].toString();
          case "disposalFacilitiesType":
            return this.showType(v[j]);
          default:
            return v[j]
        }
      }))
    },
    parseVehicleModel(value) {
      return CarType.find((p) => p.value === value)?.label;
    },
    parsePlateColor(value) {
      return LicensePlateColor.find((p) => p.value === value)?.label;
    },
    parseUseStatus(value) {
      return value === "0" ? "启用" : "未启用";
    },
    parseCarStatus(value) {
      return value === "0" ? "空闲" : "忙碌";
    },
    parseDate(value) {
      if (value) {
        return value.replace("T", " ");
      }
      return null;
    },
    showAwps(value) {
      if (value) {
        return AnnualWasteProductionScale.find((p) => p.value === value)?.label;
      }
      return null
    },
    parseSex(value) {
      if (value) {
        return value;
      }
    },
    parseWeChat(value) {
      if (value === "0") {
        return "未绑定";
      }
      if (value === "1") {
        return "已绑定";
      }
    },
    parseUserDisable(value) {
      if (value != null) {
        return value
      }
    },
    showType(value) {
      if (value) {
        return WarehouseCategory.find((p) => p.value === value).label;
      }
      return null;
    },
    showContainerCategory(value) {
      if (value) {
        return ContainerType.find((p) => p.value === value)?.label;
      }
      return null;
    },
    showPhysicalProperties(value) {
      if (value) {
        return PhysicalProperties.find((p) => p.value === value)?.label;
      }
      return null;
    },
    showCharacteristicContent(value) {
      if (value) {
        return WasteCharacteristics.find((p) => p.value === value)?.label;
      }
      return null;
    },
    parseType(value) {
      if (value != null) {
        return MessageType.find((p) => p.value === value).label;
      }
    },
    parseStatus(value) {
      if (value != null) {
        return value;
      }
    },
  }
}
